<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="1500px"
    @close="handleClose"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <!-- 证书列表 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-table
            :data="certificateList"
            border
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column
              prop="certificateNo"
              label="证书编号"
              width="180"
            />
            <el-table-column prop="studentName" label="姓名" width="120" />
            <el-table-column prop="documentNo" label="证件编号" width="180" />
            <el-table-column prop="templateName" label="证书模板">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.certificateTemplateId"
                  placeholder="请选择模板"
                  @change="handleTemplateChange(scope.row, $event)"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="template in templateList"
                    :key="template.certificateTemplateId"
                    :label="template.certificateTemplateName"
                    :value="template.certificateTemplateId"
                  >
                    {{ template.certificateTemplateName }}
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

        <el-col :span="12">
          <div class="preview-container">
            <div class="preview-header">
              <span>预览</span>
            </div>
            <div class="preview-content">
              <CertificateTemplatePreview
                v-if="previewData"
                :template-data="previewData"
              />
              <div v-else class="no-preview">请选择模板以预览</div>
            </div>

            <!-- 分页控件 - 优化位置和样式 -->
            <div class="certificate-switch" v-if="certificateList.length > 1">
              <div class="pagination-wrapper">
                <el-pagination
                  small
                  layout="prev, pager, next"
                  :total="certificateList.length"
                  :current-page="currentPage"
                  :page-size="1"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 发布设置 -->
      <el-form-item label="是否立刻发布电子证书成绩" label-width="200px" prop="immediatePublish">
        <el-radio-group v-model="form.immediatePublish">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="电子证书发布时间" label-width="200px" prop="digitalIssueTime">
        <el-date-picker
          v-model="form.digitalIssueTime"
          type="datetime"
          placeholder="选择发布时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">生成</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCertificateTemplateInfo } from "@/api/certificate/certificateTemplate";
import CertificateTemplatePreview from "@/components/Certificate/issue/CertificateTemplatePreview.vue";
export default {
  name: "GenerateElectronicCertificateDialog",
  components: { CertificateTemplatePreview },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    certificateData: {
      type: Array,
      default: () => [],
    },
    // 添加模板列表属性
    templateList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dialogTitle: "生成电子证书",
      form: {
        immediatePublish: "1",
        digitalIssueTime: null,
      },
      rules: {
        immediatePublish: [
          { required: true, message: "请选择是否立即发布", trigger: "blur" },
        ],
        digitalIssueTime: [
          {
            required: true,
            message: "请选择电子证书发布时间",
            trigger: "change",
          },
        ],
      },
      certificateList: [],
      previewData: null, // 当前预览的模板数据
      currentPage: 1,
      // currentCertificate: {},
      viewCertificateTemplateData: null,
    };
  },
  computed: {
    // 获取当前选中的模板ID（第一个证书的模板）
    currentCertificate() {
      return this.certificateList[this.currentPage - 1] || {};
    },
    previewWithCertificateData() {
      if (!this.previewData || !this.currentCertificate) {
        return null;
      }

      return {
        ...this.previewData,
        certificateData: this.currentCertificate,
      };
    },
  },
  watch: {
    certificateList: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.certificates = newVal;
          // 重置当前页为第一页
          this.currentPage = 1;
        }
      },
      deep: true,
      immediate: true,
    },
    visible(val) {
      if (val) {
        this.initData();
        // 页面打开时，如果证书列表有数据，自动加载第一个证书的模板预览
        if (
          this.certificateList.length > 0 &&
          this.certificateList[0].certificateTemplateId
        ) {
          this.loadTemplatePreview(
            this.certificateList[0].certificateTemplateId
          );
        }
      }
    },
    currentTemplateId: {
      handler(newId) {
        // 只有当当前页面是第一页时才自动加载预览
        if (newId && this.currentPage === 1) {
          this.loadTemplatePreview(newId);
        }
      },
      immediate: true,
    },
    certificateData: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.certificateList = newVal.map((item) => {
            const mappedItem = {
              ...item,
              certificateTemplateId: item.templateId || null,
            };

            // 确保模板名称正确回显
            if (
              mappedItem.certificateTemplateId &&
              this.templateList.length > 0
            ) {
              const matchedTemplate = this.templateList.find(
                (template) =>
                  template.certificateTemplateId ===
                  mappedItem.certificateTemplateId
              );
              if (matchedTemplate) {
                mappedItem.templateName =
                  matchedTemplate.certificateTemplateName;
              }
            }

            return mappedItem;
          });

          // 重置当前页并加载第一个证书的预览
          this.currentPage = 1;
          if (this.certificateList.length > 0) {
            const firstCertificate = this.certificateList[0];
            if (firstCertificate.certificateTemplateId) {
              this.loadTemplatePreview(firstCertificate.certificateTemplateId);
            }
          }
        }
      },
      deep: true,
      immediate: true,
    },
    templateList: {
      handler(newVal) {
        // 当模板列表更新时，重新处理已选证书的模板名称回显
        if (newVal && newVal.length > 0 && this.certificateList.length > 0) {
          this.certificateList = this.certificateList.map((item) => {
            if (item.certificateTemplateId) {
              const matchedTemplate = newVal.find(
                (template) =>
                  template.certificateTemplateId === item.certificateTemplateId
              );
              if (matchedTemplate) {
                return {
                  ...item,
                  templateName: matchedTemplate.certificateTemplateName,
                };
              }
            }
            return item;
          });
        }
      },
      immediate: true,
    },
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
      const certificate = this.certificateList[page - 1];
      if (certificate && certificate.certificateTemplateId) {
        this.loadTemplatePreview(certificate.certificateTemplateId);
      } else {
        this.previewData = null;
      }
    },
    initData() {
      this.form = {
        immediatePublish: "1",
        digitalIssueTime: null,
      };
      this.currentPage = 1;
    },

    handleClose() {
      this.$emit("update:visible", false);
    },

    cancel() {
      this.handleClose();
    },
    // 处理模板选择变化
    handleTemplateChange(row, templateId) {
      if (templateId) {
        const selectedTemplate = this.templateList.find(
          (template) => template.certificateTemplateId === templateId
        );
        if (selectedTemplate) {
          // 直接修改行数据，确保响应式更新
          row.certificateTemplateId = templateId;
          row.templateName = selectedTemplate.certificateTemplateName;
          // 如果当前显示的是这个证书，则更新预览
          if (row === this.currentCertificate) {
            this.loadTemplatePreview(templateId);
          }
        }
      } else {
        // 清空选择时重置数据
        row.certificateTemplateId = null;
        row.templateName = "";
        // 如果当前显示的是这个证书，则清空预览
        if (row === this.currentCertificate) {
          this.previewData = null;
        }
      }
    },
    // 根据模板ID加载模板配置并更新预览
    async loadTemplatePreview(templateId) {
      try {
        const res = await getCertificateTemplateInfo(templateId);
        this.viewCertificateTemplateData = templateData;
        let templateData = null;
        if (res.data.rows) {
          templateData = res.data.rows.find(
            (item) => item.certificateTemplateId === templateId
          );
        } else {
          templateData = res.data;
        }

        if (!templateData) {
          throw new Error(`未找到模板ID为 ${templateId} 的模板`);
        }

        // 设置预览数据
        this.previewData = {
          ...templateData,
          backgroundUrl: templateData.backgroundUrl || "",
          certificateFieldList: templateData.certificateFieldList || [],
        };

        console.log("templateData:", templateData);
        console.log("previewData:", this.previewData);

        // 更新当前证书的模板信息
        if (
          this.currentCertificate &&
          this.currentCertificate.certificateTemplateId === templateId
        ) {
          this.currentCertificate.templateName =
            templateData.certificateTemplateName;
        }
      } catch (error) {
        console.error("加载模板失败:", error);
        this.previewData = null;
        this.$message.error("模板加载失败，请检查网络连接或联系管理员");
      }
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 验证证书模板是否都已选择
          const unselectedCertificates = this.certificateList.filter(
            (item) => !item.certificateTemplateId
          );

          if (unselectedCertificates.length > 0) {
            this.$message.error("请为所有证书选择模板");
            return;
          }

          // 验证发布时间
          if (
            this.form.immediatePublish === "1" &&
            !this.form.digitalIssueTime
          ) {
            this.$message.error("请选择电子证书发布时间");
            return;
          }

          this.$emit("submit", {
            ...this.form,
            certificateIssueList: this.certificateList.map((item) => ({
              certificateIssueId: item.certificateIssueId,
              templateId: item.certificateTemplateId,
            })),
          });
          this.handleClose();
        }
      });
    },
  },
};
</script>

<style scoped>
/* 提交按钮样式优化 */
.dialog-footer {
  text-align: right;
  padding: 20px;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 表单验证提示样式 */
.el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
}

/* 分页控件样式优化 */
.pagination-wrapper {
  margin-top: 10px;
  text-align: center;
}

.el-pagination .el-pager li {
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  margin: 0 5px;
}

.el-pagination .el-pager li.active {
  background-color: #409eff;
  color: white;
}
</style>
